/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.thinktank.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.expert.domain.Expert;
import com.fzhucc.modules.expert.repository.ExpertRepository;
import com.fzhucc.modules.pms.domain.Project;
import com.fzhucc.modules.pms.domain.ProjectScore;
import com.fzhucc.modules.pms.repository.ProjectRepository;
import com.fzhucc.modules.pms.repository.ProjectScoreRepository;
import com.fzhucc.modules.thinktank.domain.*;
import com.fzhucc.modules.thinktank.domain.dto.ThinktankProjectDistributionDto;
import com.fzhucc.modules.thinktank.domain.dto.ThinktankProjectRespDto;
import com.fzhucc.modules.thinktank.repository.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-01-04
 **/
@Service
@RequiredArgsConstructor
public class ThinktankProjectLogService {

    private final ExpertRepository expertRepository;
    private final ProjectScoreRepository projectScoreRepository;
    private final ProjectRepository projectRepository;

    private final CompanyProjectLogRepository companyProjectLogRepository;

    private final AcademicianProjectLogRepository academicianProjectLogRepository;

    private final CapitalProjectLogRepository capitalProjectLogRepository;

    private final LeaderProjectLogRepository leaderProjectLogRepository;

    private final LeaderRepository leaderRepository;

    private final CompanyRepository companyRepository;

    private final CapitalRepository capitalRepository;

    private final AcademicianRepository academicianRepository;


    @Transactional
    public void dodistribution(ThinktankProjectDistributionDto thinktankProjectDistributionDto) {
        String project_id = thinktankProjectDistributionDto.getProjectId();

        List<Long> listAcademician = thinktankProjectDistributionDto.getListAcademicianId();//院士之家
        List<Long> listCapital = thinktankProjectDistributionDto.getListCapitalId();//产业资本
        List<Long> listCompany = thinktankProjectDistributionDto.getListCompanyId();//上市公司
        List<Long> listLeader = thinktankProjectDistributionDto.getListLeaderId();//产业龙头
        List<Integer> listExpert = thinktankProjectDistributionDto.getListExpertId();//专家
        Optional<Project> optionalProject = projectRepository.findById(project_id);
        if (optionalProject.isEmpty()) {
            throw new BadRequestException("项目未找到");
        }
        if (listAcademician != null && listAcademician.size() > 0) {//院士之家
            //先删除所有该项目的绑定的院士之家
            List<AcademicianProjectLog> listAcademicianProjectLog = academicianProjectLogRepository.findByProjectId(project_id);
            for (AcademicianProjectLog academicianProjectLog : listAcademicianProjectLog) {
                academicianProjectLogRepository.deleteById(academicianProjectLog.getId());
            }
            for (Long ids : listAcademician) {
                //在新增新的院士之家
                AcademicianProjectLog academicianProjectLog = new AcademicianProjectLog();
                academicianProjectLog.setProjectId(project_id);
                academicianProjectLog.setAcademicianId(ids);
                academicianProjectLog.setRelationTime(new Timestamp(new Date().getTime()));
                academicianProjectLogRepository.save(academicianProjectLog);
            }
        }

        if (listCapital != null && listCapital.size() > 0) {//产业资本
            //先删除所有该项目的绑定的产业资本
            List<CapitalProjectLog> listCapitalProjectLog = capitalProjectLogRepository.findByProjectId(project_id);
            for (CapitalProjectLog capitalProjectLog : listCapitalProjectLog) {
                capitalProjectLogRepository.deleteById(capitalProjectLog.getId());
            }
            for (Long ids : listCapital) {
                //在新增新的产业资本
                CapitalProjectLog capitalProjectLog = new CapitalProjectLog();
                capitalProjectLog.setProjectId(project_id);
                capitalProjectLog.setCapitalId(ids);
                capitalProjectLog.setRelationTime(new Timestamp(new Date().getTime()));
                capitalProjectLogRepository.save(capitalProjectLog);
            }
        }

        if (listCompany != null && listCompany.size() > 0) {//上市公司
            //先删除所有该项目的绑定的上市公司
            List<CompanyProjectLog> listCompanyProjectLog = companyProjectLogRepository.findByProjectId(project_id);
            for (CompanyProjectLog companyProjectLog : listCompanyProjectLog) {
                companyProjectLogRepository.deleteById(companyProjectLog.getId());
            }
            for (Long ids : listCompany) {
                //在新增新的上市公司
                CompanyProjectLog companyProjectLog = new CompanyProjectLog();
                companyProjectLog.setProjectId(project_id);
                companyProjectLog.setCompanyId(ids);
                companyProjectLog.setRelationTime(new Timestamp(new Date().getTime()));
                companyProjectLogRepository.save(companyProjectLog);
            }
        }

        if (listLeader != null && listLeader.size() > 0) {//产业龙头
            //先删除所有该项目的绑定的产业龙头
            List<LeaderProjectLog> listLeaderProjectLog = leaderProjectLogRepository.findByProjectId(project_id);
            for (LeaderProjectLog leaderProjectLog : listLeaderProjectLog) {
                leaderProjectLogRepository.deleteById(leaderProjectLog.getId());
            }
            for (Long ids : listLeader) {
                //在新增新的产业龙头
                LeaderProjectLog leaderProjectLog = new LeaderProjectLog();
                leaderProjectLog.setProjectId(project_id);
                leaderProjectLog.setLeaderId(ids);
                leaderProjectLog.setRelationTime(new Timestamp(new Date().getTime()));
                leaderProjectLogRepository.save(leaderProjectLog);
            }
        }

        if (listExpert != null && listExpert.size() > 0) {//专家
            //先删除所有该项目的绑定的专家
            List<ProjectScore> listProjectScore = projectScoreRepository.findByProjectId(project_id);
            for (ProjectScore projectScore : listProjectScore) {
                projectScoreRepository.deleteById(projectScore.getId());
            }
            for (Integer ids : listExpert) {
                //在新增新的专家
                ProjectScore projectScore = new ProjectScore();
                projectScore.setProject(optionalProject.get());
                projectScore.setProjectLevel(optionalProject.get().getLevel());
                Optional<Expert> expertRes = expertRepository.findById(ids);
                if (expertRes.isPresent()){
                    projectScore.setExpert(expertRes.get());
                    projectScoreRepository.save(projectScore);
                }
            }
        }
    }

    public ThinktankProjectRespDto getAllByProjectId(String projectId) {
        ThinktankProjectRespDto thinktankProjectRespDto = new ThinktankProjectRespDto();
        List<Leader> leader_list = new ArrayList<Leader>();
        List<LeaderProjectLog> list = leaderProjectLogRepository.findByProjectId(projectId);
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                LeaderProjectLog leaderProjectLog = list.get(i);
                Long leaderId = leaderProjectLog.getLeaderId();
                Optional<Leader> res = leaderRepository.findById(leaderId);
                if (res.isPresent()) {
                    leader_list.add(res.get());
                }
            }
        }


        List<Company> company_list = new ArrayList<Company>();
        List<CompanyProjectLog> list2 = companyProjectLogRepository.findByProjectId(projectId);
        if (list2 != null) {
            for (int j = 0; j < list2.size(); j++) {
                CompanyProjectLog companyProjectLog = list2.get(j);
                Long companyId = companyProjectLog.getCompanyId();
                Optional<Company> res = companyRepository.findById(companyId);
                if (res.isPresent()) {
                    company_list.add(res.get());
                }
            }
        }


        List<Capital> capital_list = new ArrayList<Capital>();
        List<CapitalProjectLog> list3 = capitalProjectLogRepository.findByProjectId(projectId);
        if (list3 != null) {
            for (int k = 0; k < list3.size(); k++) {
                CapitalProjectLog capitalProjectLog = list3.get(k);
                Long capitalId = capitalProjectLog.getCapitalId();
                Optional<Capital> res = capitalRepository.findById(capitalId);
                if (res.isPresent()) {
                    capital_list.add(res.get());
                }
            }
        }

        List<Academician> academician_list = new ArrayList<Academician>();
        List<AcademicianProjectLog> list4 = academicianProjectLogRepository.findByProjectId(projectId);
        if (list4 != null) {
            for (int h = 0; h < list4.size(); h++) {
                AcademicianProjectLog academicianProjectLog = list4.get(h);
                Long academicianId = academicianProjectLog.getAcademicianId();
                Optional<Academician> res = academicianRepository.findById(academicianId);
                if (res.isPresent()) {
                    academician_list.add(res.get());
                }
            }
        }

        thinktankProjectRespDto.setListLeader(leader_list);
        thinktankProjectRespDto.setListCompany(company_list);
        thinktankProjectRespDto.setListCapital(capital_list);
        thinktankProjectRespDto.setListAcademician(academician_list);
        return thinktankProjectRespDto;
    }
}